# coding=UTF-8
import cv2
import urllib.request
import numpy as np
from tools.alioss import AliyunOss
import io
from PIL import Image
import flask
import json
import time
from flask import Flask
from flask import request
app = Flask(__name__)



def url_to_image(url):
    # download the image, convert it to a NumPy array, and then read
    # it into OpenCV format
    resp = urllib.request.urlopen(url)
    # bytearray将数据转换成（返回）一个新的字节数组
    # asarray 复制数据，将结构化数据转换成ndarray
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    # cv2.imdecode()函数将数据解码成Opencv图像格式
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    # return the image
    return image

def heigh_temp_to_red (img):
    h,w,c= img.shape
    hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    low = np.array([0, 0, 253])
    high = np.array([0, 0, 255])
    dst = cv2.inRange(src=hsv, lowerb=low, upperb=high) # HSV高低阈值，提取图像部分区域
    kernel = np.ones((5,5),np.uint8)
    dst = cv2.morphologyEx(dst, cv2.MORPH_OPEN, kernel)
    percent = (100*(np.sum(dst)/255)/(h*w))
    img[dst == 255] = [0, 0, 255]
    return img,percent



def cal_heigh_temp(img):
    x,y= img.shape
    hist_cv = cv2.calcHist([img],[0],None,[256],[0,256])
    all_num = 0
    for  i in range(11):
        m=245+i
        all_num += hist_cv[m]
    heigh_percent = (all_num)/(x*y)
    return str(int(heigh_percent[0]*100))

def generate_figure(img,heigh_temp,debug):
    img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    gray_max=int(0+(255)/120*heigh_temp)
    gray_min=int(0+(255)/120*25)
    if gray_max>=255:
        gray_max = 255
    cv2.normalize(img,img,gray_min,gray_max,cv2.NORM_MINMAX)
    im_color = cv2.applyColorMap(img, cv2.COLORMAP_JET) #变色
    # a=0.14667
    # b=0.85778
    # c=0.9625
    #print(x,y,text)
    # pos_x = int(x * c)
    # pos_y=int(b*y)
    # cv2.rectangle(im_color, (pos_x-90, pos_y+10), (x, pos_y+60), (255, 255, 255), -1)
    # cv2.putText(im_color, text, (pos_x-88, pos_y+30), 2, 0.8, (0, 0, 0), 1, cv2.LINE_AA)
    #cv2.putText(im_color,text,(x-350,0+40),3,1.2,(255,255,255),1,cv2.LINE_AA)
    if debug ==1:
        filename = "./debug/"+str(time.time())+".jpg"
        cv2.imwrite(filename,im_color)
    return im_color

def putText(img , text):
    # text = cal_heigh_temp(img)
    # text_ ="COMPLETE: "+text+"%"
    y,x= img.shape
    cv2.putText(img,text,(x-350,0+40),3,1.2,(255,255,255),1,cv2.LINE_AA)
    return img

def get_image_bytes(img):
    img = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGRA2RGB))
    imgByte=io.BytesIO()
    img.save(imgByte,format='JPEG')
    array_bytes=imgByte.getvalue()
    return array_bytes

@app.route("/save_to_oss", methods=['POST'])
def save_to_oss():
    error_code = 0
    url = request.json.get("img_url").strip()
    oss_path = request.json.get("oss_path").strip()
    oss_path_red = oss_path.split(".jpg")[0]+"_red"+".jpg"
    heigh_temp = request.json.get("heigh_temp")
    try:
        img = url_to_image(url)
    except:
        error_code = 1

    img_ori = generate_figure(img,heigh_temp,0)
    array_bytes=get_image_bytes(img_ori)

    img_red,percent = heigh_temp_to_red(img)
    if percent <0.1:
        error_code = 3
    # cv2.imshow("1",img_red)
    # cv2.waitKey()
    array_bytes_red=get_image_bytes(img_red)


    try:
        oss_path  = aliyunoss.put_object(oss_path, array_bytes)
        oss_path_red = aliyunoss.put_object(oss_path_red, array_bytes_red)
    except:
        error_code =2
    return {"code":error_code,"oss_path": oss_path,"oss_path_red":oss_path_red}

# @app.route("/save_to_oss_debug", methods=['POST'])
# def save_to_oss_debug():
#     error_code = 0
#     url = request.json.get("img_url").strip()
#     oss_path = request.json.get("oss_path").strip()
#     heigh_temp = float(request.json.get("heigh_temp").strip())
#     try:
#         img = url_to_image(url)
#     except:
#         error_code = 1
#     img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#     text = cal_heigh_temp(img)
#     text_ ="COMPLETE: "+text+"%"
#     img = generate_figure(img,text_,1)
#     # array_bytes = img.tobytes()
#     img = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGRA2RGB))
#     imgByte=io.BytesIO()
#     img.save(imgByte,format='JPEG')
#     array_bytes=imgByte.getvalue()
#     try:
#         gen_oss_path  = aliyunoss.put_object(oss_path, array_bytes)
#     except:
#         error_code =2
#     return {"code":error_code,"oss_path": gen_oss_path,"percent":text,"requst_url":url,"requst_oss_path":oss_path}

if __name__ == '__main__':
    aliyunoss = AliyunOss()
    # url = "https://open.ys7.com/api/lapp/mq/downloadurl?appKey=a7cb8b1d58ae42cc9b841fe13d9618e5&fileKey=ISAPI_FILES/F67904528_2/20210424092404015-F67904528-2-10000-4$encrypt=2,2021-04-24T09:27:03,4007514636fa3b64a082101b618d1c9a"
    # print(save_to_oss(url,"temperature/2.jpg"))
    app.run(host='0.0.0.0', port=7009,debug = False,processes=True)




